package com.hua.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 获取数据service
 * @author sh.fan
 */
@Service
public class GetDataService {

    /**
     * 获取省名和对应的code
     * @param json_data 要处理的json数据
     * @return 处理后的map<省名，code>
     */
    public Map<String,String> city_name_code_handle(String json_data){
        Map<String,String> res = new HashMap<>();
        String[] split = json_data.split("</li>");
        for (String s : split) {
            try {
                String replace = s.replace("&quot;", "");
                String code = replace.substring(replace.indexOf("code:") + 5, replace.indexOf(","));
                String city_name = replace.substring(replace.lastIndexOf(">") +1 );
                if (!StringUtils.isEmpty(code)){
                    res.put(city_name,code);
                }
            }catch (Exception ignored){
            }
        }
        return res;
    }

    /**
     * 获取省分名
     * @return
     */
    public String get_city_name(String json_data){
        String city_name = null;
        JSONObject jsonObject = JSON.parseObject(json_data);
        List<String> list = jsonObject.getJSONObject("returndata").getList("wdnodes", String.class);
        List<String> list1 = JSON.parseObject(list.get(1)).getList("nodes", String.class);
        for (String s : list1) {
            JSONObject jsonObject1 = JSON.parseObject(s);
            try {
                city_name = jsonObject1.getString("cname");
            }catch (Exception e){
                System.out.println("aaa");
            }

        }
        return city_name;
    }

    /***
     * 获取出生率、死亡率、人口自然增长率
     * @param json_data
     * @return
     */
    public Map<String, String> get_natality(String json_data, String code){
        Map<String,String> map = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(json_data);
        List<String> list = jsonObject.getJSONObject("returndata").getList("datanodes", String.class);
        for (String s : list) {
            JSONObject res = JSON.parseObject(s);
            String string = res.getString("code");
            if (string.contains(code)){
                String year = string.substring(string.lastIndexOf(".") + 1);
                String data = res.getJSONObject("data").getString("data");
                map.put(year,data);
            }
        }
        return map;

    }
}
